<script setup>
import Footer from "@/components/common/Footer.vue";
import {ref, onMounted} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import axios from 'axios'
import qs from 'qs'

// 响应式数据
const orderTypeId = ref('')
const businessArr = ref([])
const user = ref({})
const token = localStorage.getItem("token");
// 获取路由实例
const route = useRoute()
const router = useRouter()
// 从路由中获取 orderTypeId
orderTypeId.value = route.query.orderTypeId

// 获取用户数据
const getUserData = () => {
  const userData = sessionStorage.getItem('user')
  user.value = userData ? JSON.parse(userData) : {}
}

// 根据 orderTypeId 获取商家信息
const getBusinessList = async () => {
  try {
    const response = await axios.post(
        'business/listBusinessByOrderTypeId',
        qs.stringify({
      orderTypeId: orderTypeId.value
    }),
        {
          headers: {
            "Authorization": `Bearer ${token}`,
          }})
    businessArr.value = response.data
    // 如果用户已登录，获取购物车信息
    if (user.value) {
      await listCart()
    }
  } catch (error) {
    console.error(error)
  }
}

// 获取购物车数据
const listCart = async () => {
  try {
    const response = await axios.post('cart/listCart', qs.stringify({
      userId: user.value.userId
    }),
        {
          headers: {
            "Authorization": `Bearer ${token}`,
          }})
    const cartArr = response.data
    // 遍历商家列表，更新每个商家的购物车数量
    for (const businessItem of businessArr.value) {
      businessItem.quantity = 0
      for (const cartItem of cartArr) {
        if (cartItem.businessId === businessItem.businessId) {
          businessItem.quantity += cartItem.quantity
        }
      }
    }
    // 排序（根据需要，确保商家列表排序）
    businessArr.value.sort((a, b) => a.businessName.localeCompare(b.businessName))
  } catch (error) {
    console.error(error)
  }
}

// 跳转到商家信息页面
const toBusinessInfo = (businessId) => {
  router.push({path: '/businessInfo', query: {businessId}})
}

// 初始化数据
onMounted(() => {
  getUserData()
  getBusinessList()
})
</script>

<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>商家列表</p>
    </header>
    <!-- 商家列表部分 -->
    <ul class="business">
      <li v-for="item in businessArr" @click="toBusinessInfo(item.businessId)">
        <div class="business-img">
          <img :src="item.businessImg" alt="">
          <div class="business-img-quantity" v-show="item.quantity > 0">
            {{ item.quantity }}
          </div>
        </div>
        <div class="business-info">
          <h3>{{ item.businessName }}</h3>
          <p>&#165;{{ item.starPrice }}起送 | &#165;{{ item.deliveryPrice }}配送</p>
          <p>{{ item.businessExplain }}</p>
        </div>
      </li>
    </ul>
    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 商家列表部分 ******************/
.wrapper .business {
  width: 100%;
  margin-top: 12vw;
  margin-bottom: 14vw;
}

.wrapper .business li {
  width: 100%;
  box-sizing: border-box;
  padding: 2.5vw;
  border-bottom: solid 1px #DDD;
  user-select: none;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.wrapper .business li .business-img {
  /*这里设置为相当定位，成为business-img-quantity元素的父元素*/
  position: relative;
}

.wrapper .business li .business-img img {
  width: 20vw;
  height: 20vw;
}

.wrapper .business li .business-img .business-img-quantity {
  width: 5vw;
  height: 5vw;
  background-color: red;
  color: #fff;
  font-size: 3.6vw;
  border-radius: 2.5vw;
  display: flex;
  justify-content: center;
  align-items: center;
  /*设置成绝对定位，不占文档流空间*/
  position: absolute;
  right: -1.5vw;
  top: -1.5vw;
}

.wrapper .business li .business-info {
  margin-left: 3vw;
}

.wrapper .business li .business-info h3 {
  font-size: 3.8vw;
  color: #555;
}

.wrapper .business li .business-info p {
  font-size: 3vw;
  color: #888;
  margin-top: 2vw;
}
</style>